
/**
 * 获取状态栏高度
 *
 * @returns
 */
 function getStatusBarHeightCompat () {
    let result = 0
    let resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android")
    if (resId > 0) {
      result = context.getResources().getDimensionPixelOffset(resId)
    }
    if (result <= 0) {
      result = context.getResources().getDimensionPixelOffset(R.dimen.dimen_25dp)
    }
    return result
}
function Util() {
    this.pkgName = 'com.jingdong.app.mall'    
    this.barHeight = 0
    this.img = 0
    this.logEnable = 0
    this.floaty = null
    this.storage = storages.create("jd_util");
    this.findTextDescMatchesTimeout = function (reg, timeout) {
        let c = 0
        let result = 0
        let tp = typeof reg
        if (!reg) return null
        while (c < timeout / 50) {
            if (this.logEnable) this.logInfo(c)
            if (tp == 'string') {
                result = textContains(reg).findOnce() || desc(reg).findOnce()
            } else {
                result = textMatches(reg).findOnce() || descMatches(reg).findOnce()
            }
            if (result) return result
            sleep(50)
            c++
        }
        return null
    }
    this.openApp = function (pkg, msg) {
        pkg = pkg || this.pkgName
        msg = msg || /首页/
        if(this.findTextDescMatchesTimeout(msg, 2000)) return
        let obj = this.findTextDescMatchesTimeout(/.*/, 1000)
        if (!obj || obj.packageName().indexOf(pkg) < 0){
            this.logInfo('正在打开App...', pkg)
            if (!launch(pkg)) {
                this.logInfo('可能未安装App:', pkg)
            }
            if (device.model == 'Redmi Note 4X' && pkg.indexOf('jingdong') > -1) {
                let aaa = '/' + app.getAppName(pkg) + '/'
                this.clickText(eval(aaa))
            }
            this.findTextDescMatchesTimeout(msg, 20000)
        }
    }
    this.openAndInto = function (txt, pkg, realOpen) {
        if (realOpen) this.openApp(pkg, txt)
        this.backToText(txt||/首页/)
        if (!txt) {
            this.logInfo('进入活动页面')
            return
        }
        this.clickText(txt)
    }
    this.closeDialog = function (txt) {
        let renwu = this.findTextDescMatchesTimeout(txt, 1000)
        if (!renwu) {
            return false
        }
        let x = device.width - 70, y = renwu.bounds().top - 60
        this.logInfo('关闭弹窗',x,y)
        click(x,y)
        return true
    }
    this.ocrImgInPath = function (txt, path) {
        if (!this.barHeight) {
            this.barHeight = getStatusBarHeightCompat()
        }
        if (!path) return
        this.img && this.img.recycle()
        this.img = images.read(path)
        if (!this.img ) {
          toastLog('截图失败')
          return false
        }
        let result = $ocr.detect(img)
        for (let i =0; i < result.length; ++i) {
            let or = result[i]
            if (or.label.match(txt)) {
                let x = (or.bounds.left + or.bounds.right)/2
                let y = (or.bounds.top+or.bounds.bottom)/2 - this.barHeight 
                this.logInfo(or.label, x, y)
                return click(x, y)
            }
        }
        return false
    }
    this.backToText = function (text, pkgName) {
        let timeout = 2000
        let ret = false
        this.backToApp(pkgName)
        let d = new Date()
        let t = d.getTime()
        for (let i=0;i<6; ++i) {
            if (this.isMainPage()) {
                this.logInfo('已经在首页')
                break
            }
            d = new Date()
            if ((d.getTime() - t) > (1.5*60*1000)) {
                this.logInfo('等待时长', d.getTime() - t)
                recents()
                sleep(2000)
                back()
                t = d.getTime()
            }
            let renwu = this.findTextDescMatchesTimeout(text, timeout)
            if (!renwu) {
                this.logInfo('无法找到', text, '返回')
                back()
                if (i==4) {
                    sleep(400)
                    back()
                }
            } else {
                ret = true
                break
            }
        }
        return ret
    }
    this.isMainPage = function() {
        let mainPage = null
        let ele = idMatches(/.+\..+/).findOnce()
        if (ele && ele.id().indexOf('jingdong') >= 0) {
            mainPage = [/首页/,/我的/,/购物车/]
        }
        if (ele && ele.id().indexOf('jrapp') >= 0) {
            mainPage = [/去看看/,/我的/]
        }
        if (mainPage) {
            let find = true
            for (let ndx = 0; ndx < mainPage.length; ++ndx) {
                let renwu = this.findTextDescMatchesTimeout(mainPage[ndx], 1000)
                if (!renwu) {
                    find = false
                    break
                }
            }
            return find
        }
        return false
    }
    this.backToApp = function (pkg) {
        if (!pkg) return true
        let i = 5
        while (i--) {
            let ids = ''
            let ele = idContains(pkg).findOnce()// || idMatches(/([^\.]+\.?){3,10}/).findOnce() || idMatches(/([^\.]+\.?){2,10}/).depth(4).findOnce()
            if (ele) ids = ele.id()
            if (ids.indexOf(pkg) >= 0 || currentPackage().indexOf(pkg) >= 0) {
                return true
            }
            this.logInfo('want:', pkg, 'curr:', ids)
            back()
            sleep(500)
            back()
            sleep(2000)
        }
        return i
    }
    this.taskCount = {}
    this.getTasksByText = function (txt, ignores, textFinder, white) {
        let tButton = null,
            tText = '',
            tCount = 0,
            tTitle = ''
        let taskButtons = textMatches(txt).find()
        this.logInfo('寻找未完成任务...', taskButtons.length)
        if (!taskButtons.empty()) { // 如果找不到任务，直接返回
            for (let i = 0; i < taskButtons.length; i++) {
                let button = taskButtons[i]
                let lst = []
                if (textFinder) {
                    try {
                        textFinder(button, lst)
                    } catch (err) {
                        this.logInfo('查找任务异常', err)
                        continue
                    }
                } else {
                    let tmp = button.parent().child(button.indexInParent() - 1)
                    tTitle = tmp.child(0).text()
                    tText = tmp.child(1).text()
                    lst.push(tTitle, tText)
                }
                if (lst.length == 0) {
                    this.logInfo('task text len=0', i)
                    continue
                }
                tTitle = lst[0]
                if (lst.length > 1) tText = lst[1]
    
                let r = tTitle.match(/(\d)\/(\d+)/)
                if (r) {
                    tCount = (r[2] - r[1])
                } else {
                    tCount = 0
                }
    
                let filted = false
                if (ignores) {
                    for (let ndx = 0; ndx < ignores.length; ++ndx) {
                        filted = tText.match(ignores[ndx]) || tTitle.match(ignores[ndx])
                        if (filted) {
                            filted = true
                            break
                        }
                        filted = false
                    }
                }
                if (white && !filted) {
                    for (let ndx = 0; ndx < white.length; ++ndx) {
                        r = tText.match(white[ndx]) || tTitle.match(white[ndx])
                        if (!r) {
                            filted = true
                        }
                    }
                }
                if (!filted && this.taskCount[tTitle] > 11) {
                    filted = true
                }
                // if (!find && !this.validBounds(button)) {
                //     find = true
                // }
                this.logInfo('任务:', button.text(), tTitle, tCount, filted)
                if (filted) continue 
                tButton = button
                break
            }
        } else {
            this.logInfo('任务提示未找到')
        }
        if (tButton)
        this.taskCount[tTitle] = ((this.taskCount[tTitle]||0) + 1)
        return [tButton, tText, tCount, tTitle]
    }
    this.clickElement = function (ele, type) {
        if (!ele) return
        type=type||3
        let a=0
        this.setFloatyInfo({x:ele.bounds().centerX(),y:ele.bounds().centerY()}, ele.text())
        if (type&1) {
            let txt = ele.text()
            a=ele.click()
            sleep(1000)
            if (a) {
                let b = this.findTextDescMatchesTimeout(txt, 500)
                if (!b || !b.visibleToUser() || !this.sameRect(ele.bounds(), b.bounds())) {
                    this.logInfo('by click')
                    return a
                }
            }
        }
        if ((type&2) && ele.visibleToUser() && this.validBounds(ele, 1)) {
            this.logInfo(ele.bounds().centerX(), ele.bounds().centerY())
            click(ele.bounds().centerX(), ele.bounds().centerY())
            return true
        }
        return a
    }
    this.storageOp = function(k, isPut, v) {
        if (isPut) {
            this.storage.put(k, JSON.stringify(v))
        } else {
            let s = this.storage.get(k,v)
            if (s) {
                return JSON.parse(s)
            }
            return s
        }
    }
    this.clickText = function (txt, timeoutOrAfterTxt, boundType, addon, cache) {
        let tp = typeof timeoutOrAfterTxt
        let timeout = 10000
        let afterTimeout = 3000
        let afterTxt = null
        if (tp == 'number') {
            timeout = timeoutOrAfterTxt
        } else if ((timeoutOrAfterTxt instanceof Array)) {
            timeout = timeoutOrAfterTxt[0] || timeout
            afterTxt = timeoutOrAfterTxt[1] || afterTxt
            afterTimeout = timeoutOrAfterTxt[2] || afterTimeout
            // this.logInfo(txt, timeout, afterTimeout, afterTxt)
        } else {
            afterTxt = timeoutOrAfterTxt
        }
        let x=0,y=0
        if (cache) {
            let lst = this.storageOp(txt, false)
            if (lst) {
                x = lst[0]
                y = lst[1]
            }
        }
        let renwu = this.findTextDescMatchesTimeout(txt, timeout)
        if (!renwu && x === 0) {
            this.logInfo('无法找到', txt)
            return false
        }
        let r = false
        if (renwu) {
            if (!boundType) {
                this.logInfo('点击', txt)
                r = this.clickElement(renwu)
                this.storageOp(txt, true, [renwu.bounds().centerX(), renwu.bounds().centerY()])
            } else if (boundType == 1) {
                x=renwu.bounds().left
                y=renwu.bounds().top
            } else if (boundType == 2) {
                x=renwu.bounds().centerX()
                y=renwu.bounds().centerY()
            } else if (boundType == 3) {
                x = renwu.bounds().right
                y = renwu.bounds().bottom
            } else if (boundType == 4) {
                r = this.clickElement(renwu, 1)
            } else if (boundType == 5) {
                r = this.clickElement(renwu, 2)
            }
            if (addon && addon.length > 1) {
                x = x + addon[0]
                y = y + addon[1]
            }
            if (cache && boundType !== undefined)
                this.storageOp(txt, true, [x, y])
        }
        if (x && y) {
            this.logInfo('点击', txt, x, y)
            r = click(x, y)
            this.setFloatyInfo({x,y}, txt)
        }
        if (afterTxt) {
            renwu = this.findTextDescMatchesTimeout(afterTxt, afterTimeout)
            afterTimeout = 2000
        }
        sleep(afterTimeout)
        return r
    }
    this.validBounds = function (ele, type) {
        type = type || 3
        if (type&1) {
            if (ele.bounds().centerX() < 0) {
                return false
            }
            if (ele.bounds().centerY() < 0) {
                return false
            }
        }
        if (type&2) {
            if (ele.bounds().centerX() > device.width) {
                return false
            }
            if (ele.bounds().centerY() > device.height) {
                return false
            }
        }
        return true
    }
    this.sameRect = function (rect1, rect2) {
        return (rect1.top == rect2.top && 
          rect1.left == rect2.left && 
          rect2.right == rect1.right && 
          rect1.bottom == rect2.bottom)
    }
    this.closeDialog = function(regx, timeout, x) {
        timeout = timeout || 2000
        const times = 40
        cnt = times
        x= x || (device.width-80)
        let y=100
        let sub = 50
        while (cnt--) {
            let ele = myutil.findTextDescMatchesTimeout(regx, timeout)
            if (ele) {
                this.logInfo('dialog pos:', x, y)
                this.setFloatyInfo(null, 'X')
                click(x, y)
                this.setFloatyInfo({x,y}, 'X')
                if (y > ele.bounds().bottom) {
                    sub = 0-sub
                }
                if (y + sub < 0) {
                    sub = 0-sub
                }
                y+=sub
                sleep(500)
                if (cnt ==0 && myutil.findTextDescMatchesTimeout(regx, timeout)) {
                    cnt = times
                    y = 100
                }
                continue
            }
            break
        }
        return cnt < times-1
    }
    this.innerlog = function(msg) {
        console.log(msg)
    }
    this.logInfo = function(p1,p2,p3,p4,p5) {
        let lst = [p1,p2,p3,p4,p5]
        let msg = ''
        for (let i=0;i<lst.length;++i) {
            p1 = lst[i]
            if (p1 == undefined) {
                break
            }
            if (msg) msg += ' '
            msg += p1
        }
        if (msg) 
            this.innerlog(msg)
    }
    this.qywxBotNotify = function (text, desp, QYWX_KEY) {
        let url = `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${QYWX_KEY}`
        let data = {
            msgtype: 'text',
            text: {
                content: ` ${text}\n\n${desp}`,
            }
        }
        const options = {
            headers: {
            'Content-Type': 'application/json',
            }
        };
        let rsp = http.postJson(url, data, options)
        if (rsp.statusCode == 200) {
            this.logInfo('企业微信发送通知消息成功🎉。');
        } else {
            this.logInfo('企业微信发送通知消息失败！！', rsp.body.string());
        }
    }
    this.setFloaty = function(floaty) {
        this.floaty = floaty
    }
    this.setFloatyInfo = function (position, text) {
        if (!this.floaty) return
        if (text == undefined) {
            return
        }
        if (!position) {
            if (this.floaty.hide)
                this.floaty.hide()
            else
                this.floaty.setFloatyInfo({x:100,y:100}, '--')
            return
        }
        position.x += 5
        this.floaty.setFloatyInfo(position, text + ' ' + position.x + ' ' + position.y)
    }
    this.click = function(x, y, txt) {
        try {
            this.setFloatyInfo(null, '')
        } catch (err) {

        }
        click(x,y)
        this.setFloatyInfo({x,y:y+10}, txt)
    }
}

module.exports = new Util()

